<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="搬砖 嵌入式">
<meta property="og:type" content="website">
<meta property="og:title" content="学无止境">
<meta property="og:url" content="http://example.com/page/3/index.html">
<meta property="og:site_name" content="学无止境">
<meta property="og:description" content="搬砖 嵌入式">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="xudonglei">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/page/3/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : true,
    isPost : false,
    lang   : 'zh-CN'
  };
</script>

  <title>学无止境</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">学无止境</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Do not bb, show me the example</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content index posts-expand">
            
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2024/01/20/pysimplegui%E9%AB%98%E7%BA%A7%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2024/01/20/pysimplegui%E9%AB%98%E7%BA%A7%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/" class="post-title-link" itemprop="url">pysimplegui高级和自定义事件</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2024-01-20 10:55:19" itemprop="dateCreated datePublished" datetime="2024-01-20T10:55:19+08:00">2024-01-20</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span id="/2024/01/20/pysimplegui%E9%AB%98%E7%BA%A7%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/" class="post-meta-item leancloud_visitors" data-flag-title="pysimplegui高级和自定义事件" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2024/01/20/pysimplegui%E9%AB%98%E7%BA%A7%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2024/01/20/pysimplegui%E9%AB%98%E7%BA%A7%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>​         原文链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/wzy1935/article/details/128371394">https://blog.csdn.net/wzy1935/article/details/128371394</a></p>
<p>​        PySimpleGUI中，一般只使用按钮点击触发事件。但有时我们希望监测一些自定义事件，例如用户自己编写的回调事件。又或者，还有一些其他高级事件，例如键盘输入、鼠标移动…该怎么办呢？下面给一些解决方案：</p>
<h3 id="自定义事件"><a href="#自定义事件" class="headerlink" title="自定义事件"></a>自定义事件</h3><p>​        当我们需要手动触发事件循环时，可以使用 windows 的 write_event_value 方法：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201120135.png" style="zoom:80%;">

<p>​        我们可以在其他线程触发自定义事件：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"><span class="keyword">import</span> threading, time</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">looping</span>(<span class="params">window</span>):</span></span><br><span class="line">    called = <span class="number">0</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        called += <span class="number">1</span></span><br><span class="line">        time.sleep(<span class="number">1</span>)</span><br><span class="line">        window.write_event_value(<span class="string">&#x27;loop_event&#x27;</span>, &#123;<span class="string">&#x27;called&#x27;</span>: called&#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">txt = sg.Text(<span class="string">&#x27;------&#x27;</span>, key=<span class="string">&#x27;test&#x27;</span>)</span><br><span class="line">layout = [[txt]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout, finalize=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">threading.Thread(target=looping, args=(window,)).start()</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    print(event, value) <span class="comment"># 打印所有触发的事件</span></span><br></pre></td></tr></table></figure>
<p>可以看到打印结果如下：</p>
<p>loop_event {‘loop_event’: {‘called’: 1}}<br>loop_event {‘loop_event’: {‘called’: 2}}<br>loop_event {‘loop_event’: {‘called’: 3}}<br>loop_event {‘loop_event’: {‘called’: 4}}<br>loop_event {‘loop_event’: {‘called’: 5}}<br>…</p>
<h3 id="控件交互事件"><a href="#控件交互事件" class="headerlink" title="控件交互事件"></a>控件交互事件</h3><p>​        按官方文档，当控件的 enable_events 为 true 时，当该元素被交互时(例如单击，输入一个字符)，则立即生成一个事件，导致 window.read() 调用返回。例如，对一个输入框，每当输入的字符更新时，都会触发事件。下面是示例代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">inp = sg.Input(enable_events=<span class="literal">True</span>, key=<span class="string">&#x27;input1&#x27;</span>)</span><br><span class="line">layout = [[inp]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout)</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    print(<span class="string">&#x27;EVENTS: &#x27;</span>,event)</span><br></pre></td></tr></table></figure>
<p>这时在每个在输入框里的键盘输入都会被检测到。</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201220473.png" style="zoom:67%;">

<h3 id="全局键盘事件"><a href="#全局键盘事件" class="headerlink" title="全局键盘事件"></a>全局键盘事件</h3><p>​        对于 window 组件可以开启 return_keyboard_events 对键盘进行全局监听。示例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">button = sg.Button(<span class="string">&#x27;test&#x27;</span>, key=<span class="string">&#x27;test&#x27;</span>)</span><br><span class="line">layout = [[button]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout, return_keyboard_events=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    print(event)</span><br></pre></td></tr></table></figure>
<p>这样就可以在event获取对应的keycode：</p>
<h3 id="bind高级事件"><a href="#bind高级事件" class="headerlink" title="bind高级事件"></a>bind高级事件</h3><p>​        然而有一些监听事件是PySimpleGUI做不到的。这时就需要调用组件的bind函数来绑定Tkinter的事件（因为PySimpleGUI是基于Tkinter开发的）。bind函数文档如下：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201231712.png" style="zoom:67%;">

<p>​        这里， bind_string 填待绑定的tkinter事件名（event sequences）。python-course站点给出了一些示例：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201231656.png" style="zoom:67%;">

<p>​        key_modifier 用来填写给event返回的附加值。例如，一个按钮控件的 key 是 btn，bind 函数里的 key_modifier 是_move，那么 bind 事件触发时，在事件循环里获取的event值就是 btn_move 。</p>
<p>​        下面是一个完整的bind示例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">button = sg.Button(<span class="string">&#x27;TEST&#x27;</span>, key=<span class="string">&#x27;test&#x27;</span>)  <span class="comment"># 必须设置 key</span></span><br><span class="line">layout = [[button]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout, finalize=<span class="literal">True</span>)  <span class="comment"># 必须设置 finalize</span></span><br><span class="line"></span><br><span class="line">button.bind(<span class="string">&#x27;&lt;Motion&gt;&#x27;</span>, <span class="string">&#x27;_move&#x27;</span>)  <span class="comment"># 绑定鼠标移动的事件</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    print(<span class="string">&#x27;EVENTS: &#x27;</span>, event)</span><br></pre></td></tr></table></figure>
<p>​        这里给按钮绑定了 <Motion> 事件，当鼠标在按钮上移动时，就会触发事件。因为 key_modifier 是 _move ，所以事件名为 test_move 。打印结果如下：</Motion></p>
<p>EVENTS:  test_move<br>EVENTS:  test_move<br>EVENTS:  test_move<br>EVENTS:  test_move<br>…</p>
<p>​        这里要注意的是，由于bind属于对组件的动态操作，所以调用时必须确保窗体构建完毕，因此需要给window 加上 finalize 。</p>
<h3 id="获取bind事件值"><a href="#获取bind事件值" class="headerlink" title="获取bind事件值"></a>获取bind事件值</h3><p>​        可惜，可以看出，在上面的示例中，我们在事件循环中只能获取事件名，但不能获取事件值。什么是事件值？一般来说，当一个事件触发时，我们还希望获得事件的具体情况。例如，当鼠标在控件上移动时，我们更希望知道鼠标的位置——不然只知道鼠标在移动有什么用？像这种事件的具体信息都会打包成一个事件值。<br>​        这时，我们可以使用控件的 user_bind_event 属性。当用户自定义的 bind 事件触发时，user_bind_event 会更新为本次事件的事件值。这里的事件值对象是tkinter里的 Event 类构造出的对象。可以通过 user_bind_event.x 和 user_bind_event.y 来获取鼠标当时的位置。看如下示例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">button = sg.Button(<span class="string">&#x27;test&#x27;</span>, key=<span class="string">&#x27;test&#x27;</span>)  <span class="comment"># 必须设置 key</span></span><br><span class="line">layout = [[button]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout, finalize=<span class="literal">True</span>)  <span class="comment"># 必须设置 finalize</span></span><br><span class="line"></span><br><span class="line">button.bind(<span class="string">&#x27;&lt;Motion&gt;&#x27;</span>, <span class="string">&#x27;_move&#x27;</span>)  <span class="comment"># 绑定鼠标移动的事件</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;test_move&#x27;</span>:</span><br><span class="line">        print(<span class="string">&#x27;Mouse at:&#x27;</span>, button.user_bind_event.x, button.user_bind_event.y)</span><br></pre></td></tr></table></figure>
<p>​        鼠标在 button 上移动时， test_move 事件被触发，同时 button 的 user_bind_event 也会更新。此时便能获取鼠标的位置。输出如下：</p>
<p>Mouse at: 10 1<br>Mouse at: 11 1<br>Mouse at: 12 1<br>Mouse at: 13 1<br>Mouse at: 14 2<br>Mouse at: 15 3<br>…</p>
<h3 id="例1-滚轮事件"><a href="#例1-滚轮事件" class="headerlink" title="例1 - 滚轮事件"></a>例1 - 滚轮事件</h3><p>​        我们用两个例子来说明如何自定义事件。第一个例子是一个文本控件，当鼠标滚轮在文本上上滚动时，文本显示UP，反之显示DOWN。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">txt = sg.Text(<span class="string">&#x27;------&#x27;</span>, key=<span class="string">&#x27;test&#x27;</span>)</span><br><span class="line">layout = [[txt]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout, finalize=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">txt.bind(<span class="string">&#x27;&lt;MouseWheel&gt;&#x27;</span>, <span class="string">&#x27;_wheel&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;test_wheel&#x27;</span>:</span><br><span class="line">        bind_event = txt.user_bind_event</span><br><span class="line">        print(bind_event)</span><br></pre></td></tr></table></figure>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201509367.png" style="zoom:67%;">

<p>​        不难看出，使用 delta 属性可以获知滚轮的位移。正数就是向上滚，反之就是向下。因此，加入判断即可：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> bind_event.delta &gt; <span class="number">0</span>:</span><br><span class="line">    txt.update(<span class="string">&#x27;UP&#x27;</span>)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    txt.update(<span class="string">&#x27;DOWN&#x27;</span>)</span><br></pre></td></tr></table></figure>
<h3 id="例2-长按事件"><a href="#例2-长按事件" class="headerlink" title="例2 - 长按事件"></a>例2 - 长按事件</h3><p>​        接下来，我们为按钮编写一个长按事件，当按住按钮时，事件就一直被触发。</p>
<p>​        虽然Tkinter里没有长按事件的定义，但我们可以监控鼠标按下和松开的事件。这里用到的 bind_string 是 <Button-1> 和 <ButtonRelease-1> 。由于按钮的默认事件就是ButtonRelease，所以我们不用bind这个事件：</ButtonRelease-1></Button-1></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 绑定按钮按下的事件</span></span><br><span class="line">button.bind(<span class="string">&#x27;&lt;Button-1&gt;&#x27;</span>, <span class="string">&#x27;-down&#x27;</span>)</span><br><span class="line"><span class="comment"># button按钮松开的事件就是原生事件，无需绑定，其他元素需要</span></span><br><span class="line"><span class="comment"># button.bind(&#x27;&lt;ButtonRelease-1&gt;&#x27;, &#x27;-up&#x27;)</span></span><br></pre></td></tr></table></figure>
<p>​        通过这两个事件的触发，我们定义一个flag来表示按钮是否在按下状态。如果是，就反复触发按钮按下的事件。我们用额外的线程来实现：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">test_pressed_flag = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">trigger_callback</span>(<span class="params">window</span>):</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        time.sleep(<span class="number">0.1</span>)</span><br><span class="line">        <span class="keyword">if</span> test_pressed_flag:</span><br><span class="line">            window.write_event_value(<span class="string">&#x27;test-pressed&#x27;</span>, &#123;&#125;)</span><br><span class="line"></span><br><span class="line">threading.Thread(target=trigger_callback, args=(window,)).start()</span><br></pre></td></tr></table></figure>
<p>​        接着在事件循环中更新这个flag：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;test-down&#x27;</span>:  <span class="comment"># mouse down</span></span><br><span class="line">        test_pressed_flag = <span class="literal">True</span></span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;test&#x27;</span>:  <span class="comment"># mouse up</span></span><br><span class="line">        test_pressed_flag = <span class="literal">False</span></span><br><span class="line">    print(event)</span><br></pre></td></tr></table></figure>
<p>​        完整代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"><span class="keyword">import</span> threading, time</span><br><span class="line"></span><br><span class="line">button = sg.Button(<span class="string">&#x27;test&#x27;</span>, key=<span class="string">&#x27;test&#x27;</span>)  <span class="comment"># 必须设置 key</span></span><br><span class="line">layout = [[button]]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;test&#x27;</span>, layout, finalize=<span class="literal">True</span>)  <span class="comment"># 必须设置 finalize</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 绑定按钮按下的事件</span></span><br><span class="line">button.bind(<span class="string">&#x27;&lt;Button-1&gt;&#x27;</span>, <span class="string">&#x27;-down&#x27;</span>)</span><br><span class="line"><span class="comment"># button按钮松开的事件就是原生事件，无需绑定，其他元素需要</span></span><br><span class="line"><span class="comment"># button.bind(&#x27;&lt;ButtonRelease-1&gt;&#x27;, &#x27;-up&#x27;)</span></span><br><span class="line"></span><br><span class="line">test_pressed_flag = <span class="literal">False</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">trigger_callback</span>(<span class="params">window</span>):</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        time.sleep(<span class="number">0.1</span>)</span><br><span class="line">        <span class="keyword">if</span> test_pressed_flag:</span><br><span class="line">            window.write_event_value(<span class="string">&#x27;test-pressed&#x27;</span>, &#123;&#125;)</span><br><span class="line"></span><br><span class="line">threading.Thread(target=trigger_callback, args=(window,)).start()</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: exit()</span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;test-down&#x27;</span>:  <span class="comment"># mouse down</span></span><br><span class="line">        test_pressed_flag = <span class="literal">True</span></span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;test&#x27;</span>:  <span class="comment"># mouse up</span></span><br><span class="line">        test_pressed_flag = <span class="literal">False</span></span><br><span class="line">    print(event)</span><br></pre></td></tr></table></figure>
<p>打印结果：</p>
<p>test-down<br>test-pressed<br>test-pressed<br>test-pressed<br>test-pressed<br>test</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2024/01/20/pysimplegui%E4%BA%8B%E4%BB%B6%E9%80%BB%E8%BE%91/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2024/01/20/pysimplegui%E4%BA%8B%E4%BB%B6%E9%80%BB%E8%BE%91/" class="post-title-link" itemprop="url">pysimplegui事件逻辑</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2024-01-20 10:15:19" itemprop="dateCreated datePublished" datetime="2024-01-20T10:15:19+08:00">2024-01-20</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span id="/2024/01/20/pysimplegui%E4%BA%8B%E4%BB%B6%E9%80%BB%E8%BE%91/" class="post-meta-item leancloud_visitors" data-flag-title="pysimplegui事件逻辑" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2024/01/20/pysimplegui%E4%BA%8B%E4%BB%B6%E9%80%BB%E8%BE%91/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2024/01/20/pysimplegui%E4%BA%8B%E4%BB%B6%E9%80%BB%E8%BE%91/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>​         原文链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/wzy1935/article/details/124622552">https://blog.csdn.net/wzy1935/article/details/124622552</a></p>
<p>​        我们已经知道了PySimpleGUI使用事件循环来处理GUI事件，这里，我们考虑怎么把我们的功能代码和显示代码分离，以及解决多线程问题。</p>
<h3 id="事件循环"><a href="#事件循环" class="headerlink" title="事件循环"></a>事件循环</h3><p>我们用一个简单的例子来回顾一遍我们学过了什么。我们简单的来写一个计算器：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">progress = sg.ProgressBar(<span class="number">100</span>)</span><br><span class="line">num1_inp = sg.Input(size=<span class="number">5</span>)</span><br><span class="line">num2_inp = sg.Input(size=<span class="number">5</span>)</span><br><span class="line">result_txt = sg.Text()</span><br><span class="line">add_btn = sg.Button(<span class="string">&#x27;add&#x27;</span>)</span><br><span class="line"></span><br><span class="line">layout = [</span><br><span class="line">    [num1_inp, num2_inp, result_txt],</span><br><span class="line">    [progress],</span><br><span class="line">    [add_btn]</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">window = sg.Window(<span class="string">&#x27;slow calculator&#x27;</span>, layout)</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;add&#x27;</span>:</span><br><span class="line">        num1 = <span class="built_in">int</span>(num1_inp.get())</span><br><span class="line">        num2 = <span class="built_in">int</span>(num2_inp.get())</span><br><span class="line">        result_txt.update(<span class="built_in">str</span>(num1 + num2))</span><br></pre></td></tr></table></figure>
<p>我们可以看到，确实可以正常运行：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201019426.png" style="zoom:80%;">

<p>但是很明显，这不是一个好的代码规范。我们把GUI代码和逻辑代码混写在一起，现在看起来代码还可以，等我们要实现的功能多了，代码可就要向“屎山”进化了。我们先把界面响应和功能实现分别抽离出来：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># omitted...</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span>(<span class="params">a, b</span>):</span></span><br><span class="line">    <span class="keyword">return</span> a + b</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_btn_click</span>():</span></span><br><span class="line">    num1 = <span class="built_in">int</span>(num1_inp.get())</span><br><span class="line">    num2 = <span class="built_in">int</span>(num2_inp.get())</span><br><span class="line">    result_txt.update(add(num1, num2))</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;add&#x27;</span>:</span><br><span class="line">        add_btn_click()</span><br></pre></td></tr></table></figure>
<p>​        我们这次把功能代码 add() 和界面触发 add_btn_click() 单独写成一个方法，这样GUI和功能实现就不会相互干扰，你就可以专注不同部分的代码编写了。这时，功能代码完全可以单独抽到一个文件里编写，再也不用看着GUI代码头疼了。当然，这里的代码还可以做的更好：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"><span class="keyword">import</span> api</span><br><span class="line"></span><br><span class="line"><span class="comment"># omitted...</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_btn_click</span>(<span class="params">value</span>):</span></span><br><span class="line">    num1 = <span class="built_in">int</span>(num1_inp.get())</span><br><span class="line">    num2 = <span class="built_in">int</span>(num2_inp.get())</span><br><span class="line">    result_txt.update(api.add(num1, num2))</span><br><span class="line"></span><br><span class="line">event_callbacks = &#123;</span><br><span class="line">    <span class="string">&#x27;add&#x27;</span>: add_btn_click</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> event <span class="keyword">in</span> event_callbacks:</span><br><span class="line">        event_callbacks[event](value)</span><br></pre></td></tr></table></figure>
<p>​        这次，我们把功能代码单独放在了外部文件 api.py 里。并且，添加了一个event_callbacks的map，以后只需要管理这个map就好了！</p>
<h3 id="长时任务"><a href="#长时任务" class="headerlink" title="长时任务"></a>长时任务</h3><p>​        接下来的问题也是编写GUI头疼的一大难题：长时任务。当你的功能代码很耗时的时候，GUI就会直接卡在那里…看下面的代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span>(<span class="params">a, b</span>):</span></span><br><span class="line">    time.sleep(<span class="number">5</span>)</span><br><span class="line">    <span class="keyword">return</span> a + b</span><br></pre></td></tr></table></figure>
<p>假设我们的大聪明功能 add 非常耗时，算一次加法要5秒。按照之前的代码，界面就真的会卡住5秒…</p>
<p>​        一个常见的解决方案是多线程。这里需要注意的是， <strong>谨慎使用多线程！！</strong> 看官方的解释：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201027979.png" style="zoom:80%;">

<p>当然了，这里的意思不是说不能用，只是说最好确保GUI线程是主线程。</p>
<h4 id="perform-long-operation（推荐）"><a href="#perform-long-operation（推荐）" class="headerlink" title="perform_long_operation（推荐）"></a>perform_long_operation（推荐）</h4><p>​        使用 window.perform_long_operation 可以更简单的解决问题。我们在事件循环里使用它。<strong>第一个参数是需要执行的函数，第二个参数是执行后需要触发的事件</strong>。对应函数的返回值会作为window.read()获得的value。和刚刚几乎一样的代码，只不过没有用多线程：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"><span class="keyword">import</span> api</span><br><span class="line"></span><br><span class="line"><span class="comment"># omitted...</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_btn_click</span>(<span class="params">value</span>):</span></span><br><span class="line">    num1 = <span class="built_in">int</span>(num1_inp.get())</span><br><span class="line">    num2 = <span class="built_in">int</span>(num2_inp.get())</span><br><span class="line">    window.perform_long_operation(<span class="keyword">lambda</span> :api.add(num1, num2), <span class="string">&#x27;add_output&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_output</span>(<span class="params">value</span>):</span></span><br><span class="line">    result_txt.update(<span class="built_in">str</span>(value[<span class="string">&#x27;add_output&#x27;</span>]))</span><br><span class="line"></span><br><span class="line">event_callbacks = &#123;</span><br><span class="line">    <span class="string">&#x27;add&#x27;</span>: add_btn_click,</span><br><span class="line">    <span class="string">&#x27;add_output&#x27;</span>: add_output</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> event <span class="keyword">in</span> event_callbacks:</span><br><span class="line">        event_callbacks[event](value)</span><br></pre></td></tr></table></figure>
<p>​        这里注意，当需要让perform_long_operation触发带参方法时，需要使用lambda。直接按上文写法就好了。</p>
<h4 id="偷懒写法（不推荐）"><a href="#偷懒写法（不推荐）" class="headerlink" title="偷懒写法（不推荐）"></a>偷懒写法（不推荐）</h4><p>​        这里就直接把要更新的组件给传进新线程了，新线程里会直接调用组件的方法来修改值。下面的代码使用了perform_long_operation直接让add_btn_click在新进程里调用，这样连接收值的事件都不用了，直接在新线程里修改result_txt。当然不推荐这种写法，虽然我在测试里是可以这样成功运行，但官方貌似没有这种示例，所以可能有bug。这次是完整的代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"><span class="keyword">import</span> api</span><br><span class="line"></span><br><span class="line">progress = sg.ProgressBar(<span class="number">100</span>)</span><br><span class="line">num1_inp = sg.Input(size=<span class="number">5</span>)</span><br><span class="line">num2_inp = sg.Input(size=<span class="number">5</span>)</span><br><span class="line">result_txt = sg.Text()</span><br><span class="line">add_btn = sg.Button(<span class="string">&#x27;add&#x27;</span>)</span><br><span class="line"></span><br><span class="line">layout = [</span><br><span class="line">    [num1_inp, num2_inp, result_txt],</span><br><span class="line">    [progress],</span><br><span class="line">    [add_btn]</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">window = sg.Window(<span class="string">&#x27;slow calculator&#x27;</span>, layout)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_btn_click</span>(<span class="params">value</span>):</span> <span class="comment"># multi-thread this method directly</span></span><br><span class="line">    num1 = <span class="built_in">int</span>(num1_inp.get())</span><br><span class="line">    num2 = <span class="built_in">int</span>(num2_inp.get())</span><br><span class="line">    output = api.add(num1, num2)</span><br><span class="line">    result_txt.update(<span class="built_in">str</span>(output))</span><br><span class="line"></span><br><span class="line">event_callbacks = &#123;</span><br><span class="line">    <span class="string">&#x27;add&#x27;</span>: add_btn_click</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> event <span class="keyword">in</span> event_callbacks:</span><br><span class="line">        window.perform_long_operation(<span class="keyword">lambda</span> :event_callbacks[event](value), <span class="string">&#x27;&#x27;</span>)</span><br></pre></td></tr></table></figure>
<p>不过确实很方便就是了，目前我也没碰着过bug，写写代码自用应该没有什么问题。</p>
<h3 id="进度条"><a href="#进度条" class="headerlink" title="进度条"></a>进度条</h3><p>​        最后以一个常见需求结束吧。进度条需要功能代码运行时实时提醒界面更新进度条的值。可以用write_event_value实现，也可以偷懒直接把进度条组件作为入参修改值。这里还是用偷懒写法了（因为真的懒…），所以直接在偷懒写法的版本上做修改了。</p>
<p>​        修改add方法，现在add时同时更新进度条：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span>(<span class="params">a, b, progress_bar</span>):</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">100</span>):</span><br><span class="line">        time.sleep(<span class="number">0.05</span>)</span><br><span class="line">        progress_bar.update(i+<span class="number">1</span>)</span><br><span class="line">    <span class="keyword">return</span> a+b</span><br></pre></td></tr></table></figure>
<p>​        把进组条组件传进去：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_btn_click</span>(<span class="params">value</span>):</span></span><br><span class="line">    num1 = <span class="built_in">int</span>(num1_inp.get())</span><br><span class="line">    num2 = <span class="built_in">int</span>(num2_inp.get())</span><br><span class="line">    output = api.add(num1, num2, progress)</span><br><span class="line">    result_txt.update(<span class="built_in">str</span>(output))</span><br></pre></td></tr></table></figure>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2024/01/20/pysimplegui%E7%BB%84%E4%BB%B6%E4%B8%8E%E5%B8%83%E5%B1%80/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2024/01/20/pysimplegui%E7%BB%84%E4%BB%B6%E4%B8%8E%E5%B8%83%E5%B1%80/" class="post-title-link" itemprop="url">pysimplegui组件与布局</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2024-01-20 09:28:12" itemprop="dateCreated datePublished" datetime="2024-01-20T09:28:12+08:00">2024-01-20</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span id="/2024/01/20/pysimplegui%E7%BB%84%E4%BB%B6%E4%B8%8E%E5%B8%83%E5%B1%80/" class="post-meta-item leancloud_visitors" data-flag-title="pysimplegui组件与布局" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2024/01/20/pysimplegui%E7%BB%84%E4%BB%B6%E4%B8%8E%E5%B8%83%E5%B1%80/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2024/01/20/pysimplegui%E7%BB%84%E4%BB%B6%E4%B8%8E%E5%B8%83%E5%B1%80/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>​         原文链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/wzy1935/article/details/123437255">https://blog.csdn.net/wzy1935/article/details/123437255</a></p>
<h3 id="功能组件"><a href="#功能组件" class="headerlink" title="功能组件"></a>功能组件</h3><p>​        布局前，我们先来看 PySimpleGUI 提供了哪些基础组件。这些高频组件几乎每次都会用到，所以还是把如何使用它们描述清楚比较合适。</p>
<h4 id="公有属性"><a href="#公有属性" class="headerlink" title="公有属性"></a>公有属性</h4><p>​        size 接受一个int元组。第一位表示宽度，第二位表示高度。宽和高一般以字符为计量单位。例如，下面的文本显示结果如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line">text = sg.Text(<span class="string">&#x27;-----/////-----&#x27;</span>, size=(<span class="number">5</span>,<span class="number">3</span>), font=<span class="string">&#x27;Consolas&#x27;</span>)</span><br><span class="line"><span class="comment"># 注意！只有等线类字体才有每个字符等间距的效果，其他类型字体可能会有偏差。</span></span><br></pre></td></tr></table></figure>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401200937930.png" style="zoom:80%;">

<h4 id="按钮（Button）"><a href="#按钮（Button）" class="headerlink" title="按钮（Button）"></a>按钮（Button）</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">button = sg.Button(<span class="string">&#x27;button_name&#x27;</span>, disabled=<span class="literal">False</span>)</span><br></pre></td></tr></table></figure>
<p>disabled 参数表示按钮是否被禁用。若为True，则不能被点击。</p>
<h4 id="文本（Text）"><a href="#文本（Text）" class="headerlink" title="文本（Text）"></a>文本（Text）</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">text = sg.Text(<span class="string">&#x27;text&#x27;</span>)</span><br></pre></td></tr></table></figure>
<h4 id="输入框（Input）"><a href="#输入框（Input）" class="headerlink" title="输入框（Input）"></a>输入框（Input）</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">input</span> = sg.Input(<span class="string">&#x27;default_value&#x27;</span>)</span><br></pre></td></tr></table></figure>
<h4 id="多行输入框（Multiline）"><a href="#多行输入框（Multiline）" class="headerlink" title="多行输入框（Multiline）"></a>多行输入框（Multiline）</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">multi = sg.Multiline(<span class="string">&#x27;default_value&#x27;</span>)</span><br></pre></td></tr></table></figure>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401200946883.png" style="zoom:80%;">

<h4 id="列表（Listbox）"><a href="#列表（Listbox）" class="headerlink" title="列表（Listbox）"></a>列表（Listbox）</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">list_view = sg.Listbox([<span class="string">&#x27;item 1&#x27;</span>, <span class="string">&#x27;item 2&#x27;</span>])</span><br></pre></td></tr></table></figure>
<p><img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401200951096.png"></p>
<h3 id="布局"><a href="#布局" class="headerlink" title="布局"></a>布局</h3><p>现在我们来试试布局。假设我们要完成下面的布局：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201004220.png" style="zoom:50%;">

<p>我们先把所有组件准备好吧：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">add = sg.Button(<span class="string">&#x27;Add&#x27;</span>)</span><br><span class="line">edit = sg.Button(<span class="string">&#x27;Edit&#x27;</span>)</span><br><span class="line">save = sg.Button(<span class="string">&#x27;Save&#x27;</span>)</span><br><span class="line">delete = sg.Button(<span class="string">&#x27;Delete&#x27;</span>)</span><br><span class="line">list_view = sg.Listbox([<span class="number">0</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>])</span><br><span class="line">multi = sg.Multiline(<span class="string">&#x27;Text for 1.&#x27;</span>)</span><br></pre></td></tr></table></figure>
<h4 id="基础布局"><a href="#基础布局" class="headerlink" title="基础布局"></a>基础布局</h4><p>left = [<br>    [add, edit],<br>    [save, delete],<br>    [list_view]<br>]</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201007078.png" style="zoom:67%;">

<p>看起来并不怎么样…这时我们直接修改size即可让它摆放整齐了。进行以下修改：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">add = sg.Button(<span class="string">&#x27;Add&#x27;</span>, size=<span class="number">6</span>)</span><br><span class="line">edit = sg.Button(<span class="string">&#x27;Edit&#x27;</span>, size=<span class="number">6</span>)</span><br><span class="line">save = sg.Button(<span class="string">&#x27;Save&#x27;</span>, size=<span class="number">6</span>)</span><br><span class="line">delete = sg.Button(<span class="string">&#x27;Delete&#x27;</span>, size=<span class="number">6</span>)</span><br><span class="line">list_view = sg.Listbox([<span class="number">0</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>], size=(<span class="number">15</span>,<span class="number">12</span>))</span><br></pre></td></tr></table></figure>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201008325.png" style="zoom:80%;">

<p>这样显示就正常了。那右侧的多行文本怎么办呢？</p>
<h4 id="列布局"><a href="#列布局" class="headerlink" title="列布局"></a>列布局</h4><p>你可能会想到这样的写法：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">multi = sg.Multiline(<span class="string">&#x27;Text for 1.&#x27;</span>, size=(<span class="number">30</span>, <span class="number">17</span>))</span><br><span class="line">layout = [left, multi]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;My GUI&#x27;</span>, layout)</span><br></pre></td></tr></table></figure>
<p>但注意，这样的写法是错误的。<strong>布局只能是二维数组。</strong> 直接的布局嵌套是不允许的。那该怎么办呢？</p>
<p>我们可以使用列布局。<strong>使用列布局可以把布局转化为组件</strong>。使用例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">left_col = sg.Column(left)</span><br></pre></td></tr></table></figure>
<p>这样 <code>left_col</code> 就可以后续布局了：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">layout = [</span><br><span class="line">    [left_col, multi]</span><br><span class="line">]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;My GUI&#x27;</span>, layout)</span><br></pre></td></tr></table></figure>
<p>最后布局如下：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201012380.png" style="zoom:67%;">
      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2024/01/18/pysimplegui%E5%BC%80%E5%A7%8B%E4%B8%80/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2024/01/18/pysimplegui%E5%BC%80%E5%A7%8B%E4%B8%80/" class="post-title-link" itemprop="url">pysimplegui开始一</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2024-01-18 22:00:11" itemprop="dateCreated datePublished" datetime="2024-01-18T22:00:11+08:00">2024-01-18</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span id="/2024/01/18/pysimplegui%E5%BC%80%E5%A7%8B%E4%B8%80/" class="post-meta-item leancloud_visitors" data-flag-title="pysimplegui开始一" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2024/01/18/pysimplegui%E5%BC%80%E5%A7%8B%E4%B8%80/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2024/01/18/pysimplegui%E5%BC%80%E5%A7%8B%E4%B8%80/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>​         原文链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/wzy1935/article/details/123339285">https://blog.csdn.net/wzy1935/article/details/123339285</a></p>
<h3 id="PySimpleGUI优势"><a href="#PySimpleGUI优势" class="headerlink" title="PySimpleGUI优势"></a>PySimpleGUI优势</h3><p>​        有一说一，现在大型企业应用基本用不上这种桌面应用，所以大概只有我们一些个人程序员或者爱好者才会做吧（恼）。所以一定程度上，做 GUI 程序就是纯粹的个人爱好，界面多绚丽无所谓，我只想让我写的程序脱离命令行，在窗口运行就好了。最多就需要几个按钮文本框能解决的事，实在不想学一大堆所谓 GUI 框架的语法哲学。 PySimpleGUI 的学习成本非常低。 基本上你只需要几分钟的时间就能搭建一个像样的页面。而基于 python 这一语言又使代码非常简洁易懂。</p>
<h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><p>pip install pysimplegui</p>
<h3 id="布局"><a href="#布局" class="headerlink" title="布局"></a>布局</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">layout = [[]] <span class="comment"># 布局</span></span><br><span class="line"></span><br><span class="line">window = sg.Window(<span class="string">&#x27;My GUI&#x27;</span>, layout) <span class="comment"># 以layout为布局创建窗体</span></span><br><span class="line">event, value = window.read() <span class="comment"># 监听事件</span></span><br><span class="line">window.close() <span class="comment"># 关闭窗体</span></span><br></pre></td></tr></table></figure>
<p>直接运行这段代码我们能得到一个空窗体：</p>
<p><img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401172257922.png"></p>
<p>​        我们只需要在 layout 数组里填写想要的控件就可以布局了。我们试着创建一段文本和按钮放进去：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">my_text = sg.Text(<span class="string">&#x27;My Text&#x27;</span>)</span><br><span class="line">hello_button = sg.Button(<span class="string">&#x27;Hello&#x27;</span>)</span><br><span class="line">clear_button = sg.Button(<span class="string">&#x27;Clean&#x27;</span>)</span><br><span class="line"></span><br><span class="line">layout = [</span><br><span class="line">    [my_text],</span><br><span class="line">    [hello_button, clear_button]</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">window = sg.Window(<span class="string">&#x27;My GUI&#x27;</span>, layout)</span><br><span class="line">event, value = window.read()</span><br><span class="line">window.close()</span><br></pre></td></tr></table></figure>
<p>​        现在我们的窗口长这样：</p>
<p><img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401172303947.png"></p>
<p>布局就是这么简单除暴，layout 数组里的每一行和窗口里的行一一对应。当然，这些控件的大小样式都是可以调的，不过这是后话。</p>
<h3 id="事件"><a href="#事件" class="headerlink" title="事件"></a>事件</h3><p>​        现在我们来编写事件响应。不需要那些复杂的回调机制，因为 PySimpleGUI 直接把事件循环暴露给用户自己编写。我们每次调用 window.read() 时，程序都会阻塞在这里，直到用户对窗体做出操作。在上面的代码中，我们没有使用事件循环，所以按下任何按钮后，程序都会接着向下运行，使窗口关闭。想要让窗体运作，应该这样写：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WIN_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="comment"># 在这里写主逻辑</span></span><br><span class="line"></span><br><span class="line">window.close()</span><br></pre></td></tr></table></figure>
<p>event 和 value 获取的分别是事件和对应的值。当按下关闭按钮时，我们希望程序退出，所以我们还添加了一条对应的判断语句</p>
<p>​        试试看能不能获取到按钮点击的事件吧。编写以下代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WIN_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;Hello&#x27;</span>:</span><br><span class="line">        print(<span class="string">&#x27;Click Hello&#x27;</span>)</span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;Clean&#x27;</span>:</span><br><span class="line">        print(<span class="string">&#x27;Click Clean&#x27;</span>)</span><br><span class="line"></span><br><span class="line">window.close()</span><br></pre></td></tr></table></figure>
<p>这时点击按钮就能触发命令行输出了。PySimpleGUI <strong>默认以按钮文本作为事件名</strong>。你也可以自行给按钮设置 key，就像这样：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">hello_button = sg.Button(<span class="string">&#x27;Hello&#x27;</span>, key=<span class="string">&#x27;id1&#x27;</span>)</span><br></pre></td></tr></table></figure>
<p>后面获取的事件名就是 id1 了。</p>
<h3 id="Hello-World"><a href="#Hello-World" class="headerlink" title="Hello World"></a>Hello World</h3><p>​        我们的程序已经基本完成了！我们最后来给按钮实现逻辑。当按下 Hello 时，文本提示修改为 “Hello world!”，当按下 Clear 时，清除文本。下面就是完整的实现了：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line"><span class="comment"># layout</span></span><br><span class="line">my_text = sg.Text(<span class="string">&#x27;My Text&#x27;</span>)</span><br><span class="line">hello_button = sg.Button(<span class="string">&#x27;Hello&#x27;</span>)</span><br><span class="line">clear_button = sg.Button(<span class="string">&#x27;Clean&#x27;</span>)</span><br><span class="line">layout = [</span><br><span class="line">    [my_text],</span><br><span class="line">    [hello_button, clear_button]</span><br><span class="line">]</span><br><span class="line">window = sg.Window(<span class="string">&#x27;My GUI&#x27;</span>, layout)</span><br><span class="line"></span><br><span class="line"><span class="comment"># event</span></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WIN_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;Hello&#x27;</span>:</span><br><span class="line">        my_text.update(<span class="string">&#x27;Hello world!&#x27;</span>)</span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;Clean&#x27;</span>:</span><br><span class="line">        my_text.update(<span class="string">&#x27;&#x27;</span>)</span><br><span class="line">window.close()</span><br></pre></td></tr></table></figure>
<p>​        如果需要这段程序的web版本，可以安装 PySimpleGUIWeb 包，将第一行改成下面的代码，就可以运行它的 web 版本了：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUIWeb <span class="keyword">as</span> sg</span><br></pre></td></tr></table></figure>
<p>运行结果：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401182229817.png" style="zoom:67%;">
      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2024/01/14/%E8%8A%AF%E7%89%87%E5%86%85%E6%89%A7%E8%A1%8C-XIP%E6%8F%AD%E7%A7%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2024/01/14/%E8%8A%AF%E7%89%87%E5%86%85%E6%89%A7%E8%A1%8C-XIP%E6%8F%AD%E7%A7%98/" class="post-title-link" itemprop="url">芯片内执行-XIP揭秘</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2024-01-14 20:57:01" itemprop="dateCreated datePublished" datetime="2024-01-14T20:57:01+08:00">2024-01-14</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">嵌入式</span></a>
                </span>
            </span>

          
            <span id="/2024/01/14/%E8%8A%AF%E7%89%87%E5%86%85%E6%89%A7%E8%A1%8C-XIP%E6%8F%AD%E7%A7%98/" class="post-meta-item leancloud_visitors" data-flag-title="芯片内执行-XIP揭秘" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2024/01/14/%E8%8A%AF%E7%89%87%E5%86%85%E6%89%A7%E8%A1%8C-XIP%E6%8F%AD%E7%A7%98/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2024/01/14/%E8%8A%AF%E7%89%87%E5%86%85%E6%89%A7%E8%A1%8C-XIP%E6%8F%AD%E7%A7%98/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>​         原文链接：<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/0x6Sn2DSe-OFEJOey5GnRg">https://mp.weixin.qq.com/s/0x6Sn2DSe-OFEJOey5GnRg</a></p>
<p>​        在某个项目上，客户给我们反馈了，一些芯片工作不正常。但是发现问题随flash芯片走。把这些flash芯片给到了原厂，他们也没有发现出什么问题。</p>
<p>​        我们就把出问题的几台机器拿到，进行了分析。最后，发现和”XIP”功能有关系。</p>
<p>​        和所有快乐的童话故事一样，找到了根源，问题也就好解决了。</p>
<p>​        在这里，以前自己是了解XIP，但是总感觉又有点那么不清晰。这次遇到了相关的问题，就干脆了解清楚。</p>
<p>​        eXecute In Place，即芯片内执行，是指CPU直接从存储器中读取程序代码执行，而不用再读到内存中。应用程序可以直接在flash闪存内运行，不必再把代码读到系统RAM中。<br>​        另外，我们也可以直接使用 mcmcpy 这样的接口，直接读取flash内的数据到内存中，而不需要通过 spi_read这样特定的接口。<br>还有，一看到 XIP，就要想到“只读”。只能读，不能写！</p>
<p>​        我们先来看看常规的spi flash读操作。</p>
<p>​        cpu要通过SPI控制器（一个将spi信号和AHB总线信号进行相互转化的东西）发送：opcode+address，然后通过SPI读到需要的数据。也就是说，cpu要读取flash某个地址上的数据，仅仅知道地址信息是不够的，还要发送一个opcode给到flash。<br>（如果这个flash不是SPI的，而像内存一样有多个地址线和cpu连接，那么cpu就可以真正像读内存的方式，读flash了。这样的flash也叫并行flash。而spi nor flash最终还是要走spi，因此需要SPI控制器）</p>
<p>​        如果是XIP模式，那么CPU仅仅提供address给flash就可以了，不需要额外的opcode。</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401142056048.png" style="zoom:50%;">

<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401142057904.png" style="zoom:67%;">

<p>​        我们来看一看，CPU操作memcpy如何访问flash地址的呢？<br>​        使用memcpy的时候，相当于是 cpu 访问 xip 的那块地址，然后进行拷贝到目标地址；而cpu访问xip地址的时候，spi控制器会自己发指令给flash读到xip所在的地址；此时用memcpy的时候去拿的就是从flash读上来的数据。<br>​        对应我们来说，只要配置好spi 控制器的xip功能，然后cpu只要读了xip地址，控制器就会自己发指令来读数据。<br>​        我们来想象下这个流程：<br>​        CPU发起memcpy，因为内部访问的地址是XIP地址，触发spi控制器接管。memcpy这个时候阻塞住，spi控制器仅仅发送address给到flash（通过SPI），然后通过SPI读到需要的数据（可能会用DMA方式）。数据缓存在spi控制器配置好的内存上，然后memcpy苏醒，获取到该内存上的数据。<br>​        当你用memcpy来读取flash上的数据，在程序员角度看，就和访问内存是一模一样的。但是，内部其实做了很多转换。正是因为内部做了许多转换，因此XIP的读取速度会比真实读内存的方式慢一些。<br>​        XIP也可以直接让cpu跑只读的代码段，原理都是和一样的。都依赖于spi控制器。当然，也需要配置好flash芯片，让它进入XIP工作模式。否则cpu发出的地址都会被flash当做 opcode+address 的形式，那就会出错了。</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2024/01/14/lcd%E5%B1%8F%E5%B9%95%E9%A9%B1%E5%8A%A8IC%20ST7796/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2024/01/14/lcd%E5%B1%8F%E5%B9%95%E9%A9%B1%E5%8A%A8IC%20ST7796/" class="post-title-link" itemprop="url">lcd屏幕驱动IC ST7796</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2024-01-14 20:07:07" itemprop="dateCreated datePublished" datetime="2024-01-14T20:07:07+08:00">2024-01-14</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">嵌入式</span></a>
                </span>
            </span>

          
            <span id="/2024/01/14/lcd%E5%B1%8F%E5%B9%95%E9%A9%B1%E5%8A%A8IC%20ST7796/" class="post-meta-item leancloud_visitors" data-flag-title="lcd屏幕驱动IC ST7796" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2024/01/14/lcd%E5%B1%8F%E5%B9%95%E9%A9%B1%E5%8A%A8IC%20ST7796/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2024/01/14/lcd%E5%B1%8F%E5%B9%95%E9%A9%B1%E5%8A%A8IC%20ST7796/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>​        买的中景园电子的lcd显示屏，基本信息如下所示：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401131304042.png" style="zoom:67%;">

<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401131305628.png" style="zoom:67%;">

<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401131307919.png" style="zoom:67%;">

<p><strong>ST7796初始化命令：</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><span class="line">lcd_send_cmd( <span class="number">0xF0</span> );         <span class="comment">// Command Set Control</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x96</span>                      <span class="comment">// enable command 2 part II                </span></span><br><span class="line">&#125;, <span class="number">1</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0x36</span> );         <span class="comment">// Memory Data Access Control</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x28</span>                      <span class="comment">//横屏</span></span><br><span class="line">&#125;, <span class="number">1</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0x3A</span> );         <span class="comment">//设置颜色格式为RGB565</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x55</span></span><br><span class="line">&#125;, <span class="number">1</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xB4</span> );         <span class="comment">//Display Inversion Control</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x01</span></span><br><span class="line">&#125;, <span class="number">1</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xB1</span> );        <span class="comment">//Frame Rate Control (In Normal Mode/Full Colors)</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x80</span>,<span class="number">0x10</span></span><br><span class="line">&#125;, <span class="number">2</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xB5</span> );       <span class="comment">//Blanking Porch Control</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x1F</span>,<span class="number">0x50</span>,<span class="number">0x00</span>,<span class="number">0x20</span></span><br><span class="line">&#125;, <span class="number">4</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xB6</span> );       <span class="comment">// Display Function Control</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x8A</span>,<span class="number">0x07</span>,<span class="number">0x3B</span></span><br><span class="line">&#125;, <span class="number">3</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xC0</span> );       <span class="comment">// Power Control 1</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x80</span>,<span class="number">0x64</span></span><br><span class="line">&#125;, <span class="number">2</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xC1</span> );       <span class="comment">// Power Control 2</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x13</span></span><br><span class="line">&#125;, <span class="number">1</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xC2</span> );       <span class="comment">// Power Control 3</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0xA7</span></span><br><span class="line">&#125;, <span class="number">1</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xC5</span> );       <span class="comment">// VCOM Control</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x09</span></span><br><span class="line">&#125;, <span class="number">1</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xE8</span> );       <span class="comment">//Display Output Ctrl Adjust</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x40</span>,<span class="number">0x8a</span>,<span class="number">0x00</span>,<span class="number">0x00</span>,<span class="number">0x29</span>,<span class="number">0x19</span>,<span class="number">0xA5</span>,<span class="number">0x33</span></span><br><span class="line">&#125;, <span class="number">8</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xE0</span> );       <span class="comment">//Positive Gamma Control</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0xF0</span>,<span class="number">0x06</span>,<span class="number">0x0B</span>,<span class="number">0x07</span>,<span class="number">0x06</span>,<span class="number">0x05</span>,<span class="number">0x2E</span>,<span class="number">0x33</span>,<span class="number">0x47</span>,<span class="number">0x3A</span>,<span class="number">0x17</span>,<span class="number">0x16</span>,<span class="number">0x2E</span>,<span class="number">0x31</span></span><br><span class="line">&#125;, <span class="number">14</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xE1</span> );       <span class="comment">// Negative Gamma Control</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0xF0</span>,<span class="number">0x09</span>,<span class="number">0x0D</span>,<span class="number">0x09</span>,<span class="number">0x08</span>,<span class="number">0x23</span>,<span class="number">0x2E</span>,<span class="number">0x33</span>,<span class="number">0x46</span>,<span class="number">0x38</span>,<span class="number">0x13</span>,<span class="number">0x13</span>,<span class="number">0x2C</span>,<span class="number">0x32</span></span><br><span class="line">&#125;, <span class="number">14</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xF0</span> );</span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x3C</span>                     <span class="comment">// disable command 2 part I</span></span><br><span class="line">&#125;, <span class="number">1</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0xF0</span> );</span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x69</span>                     <span class="comment">// disable command 2 part II</span></span><br><span class="line">&#125;, <span class="number">1</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0x35</span> );        <span class="comment">// Tearing Effect Line On</span></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">&#123;</span><br><span class="line">    <span class="number">0x00</span></span><br><span class="line">&#125;, <span class="number">1</span> );</span><br><span class="line"></span><br><span class="line">lcd_send_cmd( <span class="number">0x21</span> );       <span class="comment">// Display Inversion On</span></span><br><span class="line">lcd_send_cmd( <span class="number">0x11</span> );       <span class="comment">// Sleep Out</span></span><br><span class="line">lcd_send_cmd( <span class="number">0x29</span> );       <span class="comment">// Display On</span></span><br></pre></td></tr></table></figure>
<p><strong>填充一个矩形框代码如下：</strong></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">LCD_Fill</span><span class="params">(u16 xsta,u16 ysta,u16 xend,u16 yend)</span></span></span><br><span class="line"><span class="function"></span>&#123;          </span><br><span class="line">    <span class="keyword">uint8_t</span> tx_data[<span class="number">4</span>];</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 设置Column地址 */</span></span><br><span class="line">    tx_data[<span class="number">0</span>] = xsta &gt;&gt; <span class="number">8</span>; <span class="comment">//起始地址高8位</span></span><br><span class="line">    tx_data[<span class="number">1</span>] = xsta &amp; <span class="number">0xFF</span>; <span class="comment">//起始地址低8位</span></span><br><span class="line">    tx_data[<span class="number">2</span>] = xend &gt;&gt; <span class="number">8</span>; <span class="comment">//结束地址高8位</span></span><br><span class="line">    tx_data[<span class="number">3</span>] = xend &amp; <span class="number">0xFF</span>; <span class="comment">//结束地址低8位</span></span><br><span class="line">	</span><br><span class="line">    lcd_send_cmd( <span class="number">0x2A</span> );</span><br><span class="line">    lcd_send_data( tx_data, <span class="number">4</span> );</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 设置row地址 */</span></span><br><span class="line">    tx_data[<span class="number">0</span>] = ysta &gt;&gt; <span class="number">8</span>;</span><br><span class="line">    tx_data[<span class="number">1</span>] = ysta &amp; <span class="number">0xFF</span>;</span><br><span class="line">    tx_data[<span class="number">2</span>] = yend &gt;&gt; <span class="number">8</span>;</span><br><span class="line">    tx_data[<span class="number">3</span>] = yend &amp; <span class="number">0xFF</span>;</span><br><span class="line">	</span><br><span class="line">    lcd_send_cmd( <span class="number">0x2B</span> );</span><br><span class="line">    lcd_send_data( tx_data, <span class="number">4</span> );</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 写入图像数据 */</span></span><br><span class="line">    lcd_send_cmd( <span class="number">0x2C</span> );</span><br><span class="line">    GPIO_ResetBits( BSP_LCD_GPIO_PORT, BSP_LCD_CS_GPIO ); <span class="comment">//CS=0</span></span><br><span class="line">    SPI_DataSizeConfig( SPI1, SPI_DataSize_16b );</span><br><span class="line">		<span class="keyword">for</span>(<span class="keyword">uint16_t</span> i = <span class="number">0</span>; i &lt;( xend - xsta + <span class="number">1</span> ) * ( yend - ysta + <span class="number">1</span> ); i++) </span><br><span class="line">		&#123;</span><br><span class="line">        <span class="keyword">while</span>( SPI_I2S_GetFlagStatus( SPI1, SPI_I2S_FLAG_BSY ) == SET ); <span class="comment">//等待传输完成</span></span><br><span class="line">        SPI_I2S_SendData(SPI1,  <span class="number">0x0000</span>);                 <span class="comment">//用黑色填充</span></span><br><span class="line">    &#125;</span><br><span class="line">    GPIO_SetBits( BSP_LCD_GPIO_PORT, BSP_LCD_CS_GPIO ); <span class="comment">//CS=1    </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401141518323.png" style="zoom:60%;">

<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401141519616.png" style="zoom:60%;">

<p>例子LCD_Fill(80, 80, 300, 100)效果：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401141525325.jpg" style="zoom:30%;">

<p>​        0x2A和0x4B寄存器分别需要设置4个参数，起始地址的高8为，起始地址的低8位。结束地址的高8为，结束地址的低8位。</p>
<p>通过设置这两个寄存器，共同构成了一个矩形坐标区域，就是确定了要在LCD屏幕上显示的区域。</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401142018943.png" style="zoom:67%;">

<p>接下来只需要往0x2C寄存器中写入颜色数值，即可在上述区域内显示，写入的第一个颜色值，显示在(xs,ys)坐标处，第2个颜色值显示在(xs+,ys)坐标处。</p>
<p>​        横竖屏切换只要设置MVbit：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">lcd_send_cmd( <span class="number">0x36</span> );         <span class="comment">// Memory Data Access Control</span></span><br><span class="line">   lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">   &#123;</span><br><span class="line">       <span class="number">0x08</span>                      <span class="comment">//竖屏</span></span><br><span class="line">   &#125;, <span class="number">1</span> );</span><br></pre></td></tr></table></figure>
<p>对比下同样的LCD_Fill(80, 80, 300, 100)的效果：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401142036257.jpg" style="zoom:30%;">

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2024/01/11/uint8_t%E6%95%B0%E7%BB%84%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%BA%94%E7%94%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2024/01/11/uint8_t%E6%95%B0%E7%BB%84%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%BA%94%E7%94%A8/" class="post-title-link" itemprop="url">uint8_t数组类型的应用</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2024-01-11 20:29:21" itemprop="dateCreated datePublished" datetime="2024-01-11T20:29:21+08:00">2024-01-11</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">嵌入式</span></a>
                </span>
            </span>

          
            <span id="/2024/01/11/uint8_t%E6%95%B0%E7%BB%84%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%BA%94%E7%94%A8/" class="post-meta-item leancloud_visitors" data-flag-title="uint8_t数组类型的应用" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2024/01/11/uint8_t%E6%95%B0%E7%BB%84%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%BA%94%E7%94%A8/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2024/01/11/uint8_t%E6%95%B0%E7%BB%84%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%BA%94%E7%94%A8/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
           <img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401112032834.png" style="zoom:80%;">

<p>看下面这个例子：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">lcd_send_data</span><span class="params">(<span class="keyword">const</span> <span class="keyword">uint8_t</span>* data, <span class="keyword">uint8_t</span> len)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   ......</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">lcd_send_data( ( <span class="keyword">uint8_t</span>[] )</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="number">0xA4</span>, <span class="number">0xA1</span></span><br><span class="line">    &#125;, <span class="number">2</span> );</span><br></pre></td></tr></table></figure>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2024/01/01/wxpython%E4%BD%BF%E7%94%A8opencv%E6%98%BE%E7%A4%BA%E6%91%84%E5%83%8F%E5%A4%B4%E8%A7%86%E9%A2%91%E9%97%AA%E7%83%81%E9%97%AE%E9%A2%98/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2024/01/01/wxpython%E4%BD%BF%E7%94%A8opencv%E6%98%BE%E7%A4%BA%E6%91%84%E5%83%8F%E5%A4%B4%E8%A7%86%E9%A2%91%E9%97%AA%E7%83%81%E9%97%AE%E9%A2%98/" class="post-title-link" itemprop="url">wxpython使用opencv显示摄像头视频闪烁问题</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2024-01-01 21:32:22" itemprop="dateCreated datePublished" datetime="2024-01-01T21:32:22+08:00">2024-01-01</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span id="/2024/01/01/wxpython%E4%BD%BF%E7%94%A8opencv%E6%98%BE%E7%A4%BA%E6%91%84%E5%83%8F%E5%A4%B4%E8%A7%86%E9%A2%91%E9%97%AA%E7%83%81%E9%97%AE%E9%A2%98/" class="post-meta-item leancloud_visitors" data-flag-title="wxpython使用opencv显示摄像头视频闪烁问题" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2024/01/01/wxpython%E4%BD%BF%E7%94%A8opencv%E6%98%BE%E7%A4%BA%E6%91%84%E5%83%8F%E5%A4%B4%E8%A7%86%E9%A2%91%E9%97%AA%E7%83%81%E9%97%AE%E9%A2%98/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2024/01/01/wxpython%E4%BD%BF%E7%94%A8opencv%E6%98%BE%E7%A4%BA%E6%91%84%E5%83%8F%E5%A4%B4%E8%A7%86%E9%A2%91%E9%97%AA%E7%83%81%E9%97%AE%E9%A2%98/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          Here's something encrypted, password is required to continue reading.
          <!--noindex-->
            <div class="post-button">
              <a class="btn" href="/2024/01/01/wxpython%E4%BD%BF%E7%94%A8opencv%E6%98%BE%E7%A4%BA%E6%91%84%E5%83%8F%E5%A4%B4%E8%A7%86%E9%A2%91%E9%97%AA%E7%83%81%E9%97%AE%E9%A2%98/#more" rel="contents">
                阅读全文 &raquo;
              </a>
            </div>
          <!--/noindex-->
        
      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2024/01/01/wxpython%E4%BD%BF%E7%94%A8canvas%E7%BB%98%E5%9B%BE%E7%BB%84%E4%BB%B6%E6%B7%BB%E5%8A%A0matplotlib%E7%BB%98%E5%9B%BE/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2024/01/01/wxpython%E4%BD%BF%E7%94%A8canvas%E7%BB%98%E5%9B%BE%E7%BB%84%E4%BB%B6%E6%B7%BB%E5%8A%A0matplotlib%E7%BB%98%E5%9B%BE/" class="post-title-link" itemprop="url">wxpython使用canvas绘图组件添加matplotlib绘图</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2024-01-01 13:46:12" itemprop="dateCreated datePublished" datetime="2024-01-01T13:46:12+08:00">2024-01-01</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span id="/2024/01/01/wxpython%E4%BD%BF%E7%94%A8canvas%E7%BB%98%E5%9B%BE%E7%BB%84%E4%BB%B6%E6%B7%BB%E5%8A%A0matplotlib%E7%BB%98%E5%9B%BE/" class="post-meta-item leancloud_visitors" data-flag-title="wxpython使用canvas绘图组件添加matplotlib绘图" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2024/01/01/wxpython%E4%BD%BF%E7%94%A8canvas%E7%BB%98%E5%9B%BE%E7%BB%84%E4%BB%B6%E6%B7%BB%E5%8A%A0matplotlib%E7%BB%98%E5%9B%BE/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2024/01/01/wxpython%E4%BD%BF%E7%94%A8canvas%E7%BB%98%E5%9B%BE%E7%BB%84%E4%BB%B6%E6%B7%BB%E5%8A%A0matplotlib%E7%BB%98%E5%9B%BE/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>​         直接上代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> numpy <span class="keyword">import</span> arange, sin, pi</span><br><span class="line"><span class="keyword">import</span> matplotlib</span><br><span class="line"></span><br><span class="line">matplotlib.use(<span class="string">&#x27;WXAgg&#x27;</span>)</span><br><span class="line"><span class="keyword">from</span> matplotlib.backends.backend_wxagg <span class="keyword">import</span> FigureCanvasWxAgg <span class="keyword">as</span> FigureCanvas</span><br><span class="line"><span class="keyword">from</span> matplotlib.figure <span class="keyword">import</span> Figure</span><br><span class="line"><span class="keyword">import</span> wx</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CanvasPanel</span>(<span class="params">wx.Panel</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, parent</span>):</span></span><br><span class="line">        wx.Panel.__init__(self, parent)</span><br><span class="line">        self.slider = wx.Slider(self, -<span class="number">1</span>, value=<span class="number">1</span>, minValue=<span class="number">0</span>, maxValue=<span class="number">11</span>)</span><br><span class="line">        self.slider.Bind(wx.EVT_SLIDER, self.OnSlider)</span><br><span class="line">        self.figure = Figure()</span><br><span class="line">        self.axes = self.figure.add_subplot(<span class="number">111</span>)</span><br><span class="line">        self.canvas = FigureCanvas(self, -<span class="number">1</span>, self.figure)</span><br><span class="line"></span><br><span class="line">        self.sizer = wx.BoxSizer(wx.VERTICAL)</span><br><span class="line">        self.sizer.Add(self.canvas, proportion=<span class="number">1</span>,</span><br><span class="line">                       flag=wx.LEFT | wx.TOP | wx.GROW)</span><br><span class="line">        self.sizer.Add(self.slider, proportion=<span class="number">0</span>,</span><br><span class="line">                       flag=wx.LEFT | wx.TOP | wx.GROW)</span><br><span class="line">        self.SetSizer(self.sizer)</span><br><span class="line">        self.Fit()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">OnSlider</span>(<span class="params">self, event</span>):</span></span><br><span class="line">        self.draw()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">draw</span>(<span class="params">self</span>):</span></span><br><span class="line">        t = arange(<span class="number">0.0</span>, <span class="number">3.0</span>, <span class="number">0.01</span>)</span><br><span class="line">        h = self.slider.GetValue()</span><br><span class="line">        s = h * sin(<span class="number">2</span> * pi * t)</span><br><span class="line">        self.axes.clear()</span><br><span class="line">        self.axes.plot(t, s)</span><br><span class="line">        self.canvas.draw()        <span class="comment"># 加了这句，纵坐标的值才会修改</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    app = wx.App()</span><br><span class="line">    frame = wx.Frame(<span class="literal">None</span>, title=<span class="string">&#x27;test&#x27;</span>)</span><br><span class="line">    panel = CanvasPanel(frame)</span><br><span class="line">    panel.draw()</span><br><span class="line">    frame.Show()</span><br><span class="line">    app.MainLoop()</span><br></pre></td></tr></table></figure>
<p><img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401011401439.png"></p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2023/12/31/AIR32F103%E7%A7%BB%E6%A4%8Dfreertos/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/2023/12/31/AIR32F103%E7%A7%BB%E6%A4%8Dfreertos/" class="post-title-link" itemprop="url">AIR32F103移植freertos</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2023-12-31 19:07:12" itemprop="dateCreated datePublished" datetime="2023-12-31T19:07:12+08:00">2023-12-31</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">嵌入式</span></a>
                </span>
            </span>

          
            <span id="/2023/12/31/AIR32F103%E7%A7%BB%E6%A4%8Dfreertos/" class="post-meta-item leancloud_visitors" data-flag-title="AIR32F103移植freertos" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2023/12/31/AIR32F103%E7%A7%BB%E6%A4%8Dfreertos/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2023/12/31/AIR32F103%E7%A7%BB%E6%A4%8Dfreertos/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>1.下载FreeRTOS源码，可以从官网下载源码，官网地址：<a target="_blank" rel="noopener" href="https://www.freertos.org/a00104.html">https://www.freertos.org/a00104.html</a></p>
<p>2.解压后包含的内容比较丰富，不过目录结构很清晰，主要包含两个子目录：FreeRTOS和FreeRTOS-Plus。如下所示：</p>
<p>FreeRTOS-Plus       包含FreeRTOS+组件和演示例程；<br>FreeRTOS                包含FreeRTOS实时内核源文件和演示例程。</p>
<p>3.在工程文件夹中创建FREERTOS文件夹，将下载的源码解压，进入到FreeRTOS文件夹中，将Source文件夹下的内容全部复制到刚刚创建的FREERTOS文件夹</p>
<p>​        把Source/portable文件夹下的MemMang和RVDS文件夹复制到Source目录下，如下图所示，并将Source/portable文件夹中其他内容删除。</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312311915873.png" style="zoom:67%;">

<p>​        把Source/RVDS/ARM_CM3文件夹下所有的文件复制到RVDS文件下，然后删除Source/RVDS中其他所有的文件夹（注意不要删除了刚刚复制的文件）</p>
<p>4.把保留下来的文件添加到Keil工程中，如下图所示</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312311928250.png" style="zoom:67%;">

<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202312311935723.png" style="zoom:67%;">

<p>5.网上找一个demo示例，在例子中找到里面的FreeRTOSConfig.h文件，添加到工程文件FreeRTOS文件夹下的include文件夹里。</p>
<p>6.RVDS/ARM_CM3\portmacro.h(167): error: unknown type name ‘__forceinline’</p>
<p>编译报了很多错误，最新版本的mkd不默认支持ARM_Compiler_5，而 ARM Complier 6以后只支持GNU风格的内联。<strong>使用ARM_Compiler_5编译就不错了</strong>。</p>
<p>7.复制过来的FreeRTOSConfig.h文件中默认开启了一些钩子函数，都是以Hook结尾，但并未定义，在FreeRTOSConfig.h中把configUSE_IDLE_HOOK、configUSE_TICK_HOOK、configCHECK_FOR_STACK_OVERFLOW和MALLOC_FAILED_HOOK的宏定义改为0</p>
<p>8.直接上demo代码例子：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line">TaskHandle_t task_led_handler;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Taskled</span><span class="params">(<span class="keyword">void</span> *pvParameters)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    led_init();</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>) </span><br><span class="line">		&#123;</span><br><span class="line">        led_toggle();</span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">500</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">led_task_create</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	xTaskCreate(Taskled,</span><br><span class="line">              <span class="string">&quot;LED Task&quot;</span>,</span><br><span class="line">               LED_TASK_STACK_SIZE,</span><br><span class="line">               <span class="literal">NULL</span>,</span><br><span class="line">               LED_TASK_PRORITY,</span><br><span class="line">               &amp;task_led_handler);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">TaskHandle_t task_uart_handler;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Taskuart</span><span class="params">(<span class="keyword">void</span> *pvParameters)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    UART1_Init(<span class="number">9600</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>) </span><br><span class="line">		&#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;hello\r\n&quot;</span>);</span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">uart_task_create</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	xTaskCreate(Taskuart,</span><br><span class="line">              <span class="string">&quot;Uart Task&quot;</span>,</span><br><span class="line">               UART_TASK_STACK_SIZE,</span><br><span class="line">               <span class="literal">NULL</span>,</span><br><span class="line">               UART_TASK_PRORITY,</span><br><span class="line">               &amp;task_uart_handler);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);<span class="comment">//配置中断分组</span></span><br><span class="line"></span><br><span class="line">  uart_task_create();</span><br><span class="line">  led_task_create();</span><br><span class="line">	</span><br><span class="line">  vTaskStartScheduler();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  


  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/2/"><i class="fa fa-angle-left" aria-label="上一页"></i></a><a class="page-number" href="/">1</a><a class="page-number" href="/page/2/">2</a><span class="page-number current">3</span><a class="page-number" href="/page/4/">4</a><span class="space">&hellip;</span><a class="page-number" href="/page/29/">29</a><a class="extend next" rel="next" href="/page/4/"><i class="fa fa-angle-right" aria-label="下一页"></i></a>
  </nav>



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">xudonglei</p>
  <div class="site-description" itemprop="description">搬砖 嵌入式</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">283</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">67</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xudonglei</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'BT0Qw9HcTpPv1a6cT1iDBXKz-gzGzoHsz',
      appKey     : 'LMCMh8v02JTMFAwKNRcgoizI',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-CN' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
